<?php

namespace App\Command;

use App\Base\ViewsInList;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

class LazyCreateCommand extends Command
{

    private $updateAll = 1;//覆盖更新
    private $systemTable = [
        //系统项目不允许覆盖
        "User","UserGroups","UserGroupsRole","UserLoginLog"
        ,"Admin","AdminMenu","AdminMenuUser","AdminLog"
        ,"ConfCat","PlatConfig","Role","Rules","RulesCategory"
        ,"WechatCode","WechatReply"

    ];
    private $readyTable = [
        //以下项目已完成配置不允许再覆盖
        "aaaaa","aaaaa","aaaaa","aaaaa","aaaaa","aaaaa","aaaaa"
        ,"aaaaa","aaaaa","aaaaa","aaaaa","aaaaa","aaaaa","aaaaa"
        ,"aaaaa","aaaaa","aaaaa","aaaaa","aaaaa","aaaaa"
    ];
    protected static $defaultName = 'lazy:create';

    protected function configure()
    {
        $this
            ->setDescription('生成数据库CURD')
            ->addArgument('en', InputArgument::OPTIONAL, 'Entity Name')
            ->addOption('option1', null, InputOption::VALUE_NONE, 'Option description')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $io = new SymfonyStyle($input, $output);
        $entity = $input->getArgument('en');

        if ($entity) {
            $io->note(sprintf('You passed an argument: %s', $entity));
        }
        $count = 0;
        if (!$entity) {
            $root = str_replace("src\\Command","",__DIR__);//E:\www\symfony4\src\Command
            $dirEntity = $root."src\\Entity";is_dir($dirEntity) OR mkdir($dirEntity, 0777, true);
            //查找Entity
            $entityList = scandir($dirEntity);
            foreach ($entityList as $item) {
                $array = mb_split("\.",$item);
                if ($array[count($array) - 1] != "php") {
                    continue;
                }
                $itemName = $array[0];
                if (in_array($itemName,$this->systemTable)) {
                    //系统表永远不能覆盖
                    continue;
                }
                if (in_array($itemName,$this->readyTable) && $this->updateAll == 0) {
                    //已完成的表如果开启覆盖可以覆盖
                    continue;
                }
                $this->createEntityData($itemName);
                print_r($itemName."已处理\n");
                $count ++;
            }
        }else{
            $this->createEntityData($entity);
            $count ++;
        }

        $io->success("处理了：$count 项");
    }



    public function createEntityData($itemName)
    {
        $targetBundle = "App";
        $dirTemplate = str_replace("src\\Command","LazyAdminSrc\\",__DIR__);//E:\www\symfony4\src\Command
        $LazyAdminSrcDir = $dirTemplate;//E:\www\symfony4\LazyAdminSrc\
        $dirEntity = $LazyAdminSrcDir."Entity";is_dir($dirEntity) OR mkdir($dirEntity, 0777, true);
        $dirController = $LazyAdminSrcDir."Controller";is_dir($dirController) OR mkdir($dirController, 0777, true);
//        $dirControllerCommon = $LazyAdminSrcDir."Controller\\AdminCommon";is_dir($dirControllerCommon) OR mkdir($dirControllerCommon, 0777, true);
        $dirControllerAdmin = $LazyAdminSrcDir."Controller\\Admin";is_dir($dirControllerAdmin) OR mkdir($dirControllerAdmin, 0777, true);
        $dirSetting = $LazyAdminSrcDir."Setting";is_dir($dirSetting) OR mkdir($dirSetting, 0777, true);
        $dirModel = $LazyAdminSrcDir."Model";is_dir($dirModel) OR mkdir($dirModel, 0777, true);
//        $dirModelCommon = $LazyAdminSrcDir."Model\\Common";is_dir($dirModelCommon) OR mkdir($dirModelCommon, 0777, true);
        $dirTwig = $LazyAdminSrcDir."Twig";is_dir($dirTwig) OR mkdir($dirTwig, 0777, true);
        $dirTemplate =  str_replace("LazyAdminSrc\\","",$LazyAdminSrcDir)."Template";is_dir($dirTemplate) OR mkdir($dirTemplate, 0777, true);

        //测试是否是Category类型的实体
        if (preg_match("/(.+)?Category/",$itemName) == 1) {//YY-mm-dd HH:ii:ss
            $isCat = "\\Category";
            $isCatTwig = "cat_";
        }else{
            $isCat = "";
            $isCatTwig = "";
        }

        $tableNameTable = preg_replace("/([A-Z])/","_$1",substr($itemName,1));
        $tableNameTable = substr($itemName,0,1).$tableNameTable;

//        if (in_array($itemName,$this->systemTable)){
//            return;
//        }
//        if (in_array($itemName,$this->readyTable)){
//            return;
//        }
        $entityName = "App\\Entity\\".$itemName;
        $entity = new $entityName();
        $keys = $this->toArray($entity);
        array_shift($keys);

        //2.创建Controller
        //检查文件是否存在
//        $cTpl = file_get_contents($dirTemplate.$isCat."\\SAMPLEAdminCommonController.php");
//        $cTpl = str_replace("__TARGET_BUNDLE__",$targetBundle,$cTpl);
//        $cTpl = str_replace("__TARGET_ENTITY_TABLE__",$tableNameTable,$cTpl);
//        $cTpl = str_replace("__TARGET_ENTITY__",$itemName,$cTpl);
//        file_put_contents($dirControllerCommon."\\".$itemName."CommonController.php",$cTpl);
        if (!file_exists($dirControllerAdmin."\\".$itemName."Controller.php") || $this->updateAll){
            $cTpl = file_get_contents($dirTemplate.$isCat."\\SAMPLEAdminController.php");
            $cTpl = str_replace("__TARGET_BUNDLE__",$targetBundle,$cTpl);
            $cTpl = str_replace("__TARGET_ENTITY_TABLE__",$tableNameTable,$cTpl);
            $cTpl = str_replace("__TARGET_ENTITY__",$itemName,$cTpl);
            file_put_contents($dirControllerAdmin."\\".$itemName."Controller.php",$cTpl);
        }

        //3.创建Model
//        $cTpl = file_get_contents($dirTemplate.$isCat."\\SAMPLECommonModel.php");
//        $cTpl = str_replace("__TARGET_BUNDLE__",$targetBundle,$cTpl);
//        $cTpl = str_replace("__TARGET_ENTITY__",$itemName,$cTpl);
//        file_put_contents($dirModelCommon."\\".$itemName."CommonModel.php",$cTpl);
        if (!file_exists($dirModel."\\".$itemName."Model.php") || $this->updateAll){
            $cTpl = file_get_contents($dirTemplate.$isCat."\\SAMPLEModel.php");
            $cTpl = str_replace("__TARGET_BUNDLE__",$targetBundle,$cTpl);
            $cTpl = str_replace("__TARGET_ENTITY_TABLE__",$tableNameTable,$cTpl);
            $cTpl = str_replace("__TARGET_ENTITY__",$itemName,$cTpl);
            file_put_contents($dirModel."\\".$itemName."Model.php",$cTpl);
        }

        //4-5：处理entity内部字段
        $formConfStr = "";
        $listConfArray = ["'id'"];
        $viewConfTitleStr = "";
        $viewConfRowStr = "";
        foreach ( $keys as $k => $v ) {
            $V = new ViewsInList();
            $dataConf = $V->setItem($k,$itemName)->get();
            //select 字段生成
            $dataBaseField = preg_replace("/([A-Z])/","_$1",$k);
            $listConfArray[] = "'".$dataBaseField."'";
            //管理列表title生成
            $viewConfTitleStr .= $V->createViewTitle($dataConf);
            //管理列表Row生成
            $viewConfRowStr .= $V->createViewRow($dataConf,$itemName);
            //form编辑字段生成
            $formConfStr .= $V->createAddItem($dataConf);
        }
        $listConfStr = implode(",",$listConfArray);
        $V = new ViewsInList();
        $viewConfTitleStr = $V->createViewHeadAndTail($viewConfTitleStr);
        $viewConfRowStr = $V->createViewRowHeadAndTail($viewConfRowStr,$itemName);

        //4.创建Setting
        if (!file_exists($dirSetting."\\".$itemName."Setting.php") || $this->updateAll){
            $cTpl = file_get_contents($dirTemplate.$isCat."\\SAMPLESetting.php.txt");
            $cTpl = str_replace("__TARGET_BUNDLE__",$targetBundle,$cTpl);
            $cTpl = str_replace("__TARGET_ENTITY__",$itemName,$cTpl);
            $cTpl = str_replace("__TARGET_ENTITY_TABLE__",$tableNameTable." AS ".$itemName,$cTpl);
            $cTpl = str_replace("__TARGET_TABLE__",$tableNameTable,$cTpl);
            $cTpl = str_replace("__FORM_CONF__",$formConfStr,$cTpl);
            $cTpl = str_replace("__LIST_CONF__",$listConfStr,$cTpl);
            file_put_contents($dirSetting."\\".$itemName."Setting.php",$cTpl);
        }
        //5.创建View
        $dirView = $dirTwig."\\".$itemName;is_dir($dirView) OR mkdir($dirView, 0777, true);
        $cTpl = file_get_contents($dirTemplate.$isCat."\\list.php.twig");
        $cTpl = str_replace("__TARGET_BUNDLE__",$targetBundle,$cTpl);
        $cTpl = str_replace("__TARGET_ENTITY_TABLE__",$tableNameTable,$cTpl);
        $cTpl = str_replace("__TARGET_ENTITY__",$itemName,$cTpl);
        $cTpl = str_replace("__LIST_TITLE_CONF__",$viewConfTitleStr,$cTpl);
        $cTpl = str_replace("__LIST_ROW_CONF__",$viewConfRowStr,$cTpl);
        file_put_contents($dirView."\\{$isCatTwig}list.php.twig",$cTpl);
    }

    /**
     * @param $entity
     * @return array
     */
    private  function toArray(&$entity)
    {
        if(!$entity) return[];
        $methods = (get_class_methods(get_class($entity)));
        $arrData = array();
        foreach ($methods as $method) {
            $attr = lcfirst(substr($method,3));
            $funcName = "get".ucfirst($attr);
            $arrData[$attr] = $entity->$funcName();
        }
        $entity = $arrData;
        return $arrData;
    }
}
